/*version for server*/

if (typeof(versions) == "undefined") {
    versions = {
        dev: {
            rtq: "",
            domain: QS_PROTOCOL + "rtqdev.morningstar.com/opt/",
            push: QS_PROTOCOL + "pushdev.morningstar.com"
        },
        pre: {
            rtq: "",
            domain: QS_PROTOCOL + "qspre.morningstar.com/",
            push: QS_PROTOCOL + "pushpre.morningstar.com"
        },
        release: {
            rtq: "",
            domain: QS_PROTOCOL + "quotespeed.morningstar.com/",
            push: QS_PROTOCOL + "push.morningstar.com"
        }
    };
}

if (typeof QS_SERVER_DOMAIN != 'undefined' && typeof QS_PUSH_DOMAIN != 'undefined') {
    version={
        rtq:QS_PROTOCOL + QS_SERVER_DOMAIN,
        domain: QS_PROTOCOL + QS_SERVER_DOMAIN,
        push:QS_PROTOCOL + QS_PUSH_DOMAIN
    }
}else {
    if (typeof(QS_VERSION) == "undefined") {
        version = versions.release;
    }
    else {
        version = versions[QS_VERSION];
    }
}

if(!QS){
	var QS={};
}
QS.localStorageLock=false;

var copconfigurl = version.rtq + "getCopConfig.jsp";            //to get the component config
var saveconfigurl = version.rtq + "saveWsConfig.jsp";
var removwsconfig = version.rtq + "removeConfig.jsp";
var savealertconfigurl = version.rtq + "saveAlertConfig.jsp";
//var getalertconfigurl = version.rtq + "getAlertConfig.jsp";
var setalertstausurl = version.rtq + "setAlertStaus.jsp";
var exportTimeSales = version.rtq + "exportTimeAndSaleData.jsp";
var qtpageurl = "qt.htm";
function trim(s) {
    st = s.replace(/(\s*$)/g, "");
    return st.replace(/(^\s*)/g, "");
}
var Cookies = {
     set: function(name, value) {
         var argv = arguments;
         var argc = arguments.length;
         var expires = (argc > 2) ? argv[2] : null;
         var path = (argc > 3) ? argv[3] : '/';
         var domain = (argc > 4) ? argv[4] : null;
         var secure = (argc > 5) ? argv[5] : false;
         document.cookie = name + "=" + escape(value) +
       ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
       ((path == null) ? "" : ("; path=" + path)) +
       ((domain == null) ? "" : ("; domain=" + domain)) +
       ((secure == true) ? "; secure" : "");
     },
     get: function(name) {
         var arg = name + "=";
         var alen = arg.length;
         var clen = document.cookie.length;
         var i = 0;
         var j = 0;
         while (i < clen) {
             j = i + alen;
             if (document.cookie.substring(i, j) == arg)
                 return Cookies.getCookieVal(j);
             i = document.cookie.indexOf(" ", i) + 1;
             if (i == 0)
                 break;
         }
         return null;
     },

     clear: function(name) {
         if (Cookies.get(name)) {
             var expdate = new Date();
             expdate.setTime(expdate.getTime() - (86400 * 1000 * 1));
             Cookies.set(name, "", expdate);
         }
     },

     getCookieVal: function(offset) {
         var endstr = document.cookie.indexOf(";", offset);
         if (endstr == -1) {
             endstr = document.cookie.length;
         }
         return unescape(document.cookie.substring(offset, endstr));
     }
 };

 function postRequest(url, data, ca) {
    //?usrName="+usrName+"&pw="+pwd;
    $.post(url, data, loginResult);
}

//function wsconfigArried(data) {
//    $("#profile").html(data);
//}
function calTime(dStr){//yyyy-MM-dd HH:mm:ss
	var d=dStr.split(" "),dt=d[0].split("-"),tm=d[1].split(":");
	var date=new Date(parseInt(dt[0],10),parseInt(dt[1],10)-1,parseInt(dt[2],10),parseInt(tm[0],10),parseInt(tm[1],10),parseInt(tm[2],10));
    return date.getTime();
}
function compareTime(cTime,sTime){
	if(!sTime||!cTime||sTime==''||cTime==''){
		return -1;
	}else{
		var ct=calTime(cTime),st=calTime(sTime);
		if(ct>st){
			return 1;
		}else if(ct==st){
			return 0;
		}else{
			return -1;
		}
	}
}
function getLocalStorageByKey(key){
	var val;
	if (QS.localStorageLock&&window.localStorage) {
	   val=localStorage.getItem(key+"_"+QS_UserID);
	}
	return val;
}
function save2LocalStorage(arr){
	if (QS.localStorageLock&&arr.length>0) {
	   for(var i=0,l=arr.length;i<l;i++){
	   	   localStorage.setItem(arr[i][0],arr[i][1]);
	   }
	}
}
function removeLocalStorage(keys){
    if (QS.localStorageLock&&window.localStorage) {
       for(var i=0,l=keys.length;i<l;i++){
           localStorage.removeItem(keys[i]+"_"+QS_UserID);
       }
    }
}
function getWidgets(wsId, callback) // get user's component profile list in one workspace
{
    if (QS_UserID != null) {
		var flag = false, curWList;
        if (QS.localStorageLock&&window.localStorage) { //add a lock to unify the codes between opt and pre.
            var serverTime = gWsList[wsId]["updateTime"];//DB Time
            var clientTime = localStorage.getItem("QS_CurWs_UpdatedTime_"+QS_UserID);//Client Time
            curWList = localStorage.getItem("QS_CurWs_"+QS_UserID);
			curWsId = localStorage.getItem("QS_CurWsId_"+QS_UserID);
            if (compareTime(clientTime,serverTime)>=0&& curWList && curWList != ''&&curWsId&&wsId==curWsId&&curWList!='{}') {
                flag = true;
            }
        }
        if (flag) {
            callback(curWList);
        }else{
             var data = { usrId: QS_UserID, wId: wsId };
             DBHelper.post(copconfigurl, data, callback);
        } 
    }
}
//function getCopConfig() // get user's one component profile in one workspace
//{
//    $("#profile").html();
//    var wId = $("#wsId4").val();
//    var c = $("#copId").val();
//    if (QS_UserID != null) {
//        var data = { usrId: QS_UserID, wId: wId, cId: c };
//        $.post(copconfigurl, data, wsconfigArried);
//    }
//}

function deleteWorkspace(wsId, callback) {
    if (QS_UserID != null) {
        var data = { usrId: QS_UserID, wId: wsId, tmpid:QS_UserTID};
        $.post(removwsconfig, data, callback);
    }
}
function deleteWidgets(wsId, widgetIds, callback) {
    var str = $.toJSON(widgetIds);
    if (QS_UserID != null) {
        var data = { usrId: QS_UserID, wId: wsId, profile: str, tmpid:QS_UserTID };
        $.post(removwsconfig, data, callback);
    }
}
function saveAlertConfig(profile,callback)  // return "true" success, return "false" fail.
{
 var str =  $.toJSON(profile);
 if(QS_UserID != null){
  var data={usrId:QS_UserID,profile:str, tmpid:QS_UserTID};
  $.post(savealertconfigurl,data,callback);
  }
}
//function getAlertConfig(callback)
//{ ;
//   if(QS_UserID != null){
//   var data = {usrId:QS_UserID};
//   $.post(getalertconfigurl,data,callback);
//   }
//}
if(typeof(PULL_Path)=="undefined"){
    PULL_Path="/pullservice/pull/";
}
function setAlertStaus(tic,callback)
{  
   if(QS_UserID != null){
    var cond = "{UserId:" + QS_UserID + ",CreateTime:" + tic + "}";
   var data = {cstr:cond, tmpid:QS_UserTID };
   $.post(setalertstausurl,data,callback);
   }
}

/*
 * New DataBase Helper
 * David li 090907
 */
if(typeof(QS_UserTID) == "undefined" || !QS_UserTID){QS_UserTID='';} //!IMPORTANT post it while updating/deleting data //for CROSS SITE REQUEST FORGERY
if(typeof DBHelper=='undefined'){
    DBHelper = {};
}
if(!DBHelper.URLs){
    DBHelper.URLs = {};
}
DBHelper.URLs.template = version.rtq + "template.jsp";
DBHelper.URLs.portfolio = version.rtq + "portfolio.jsp";
DBHelper.URLs.globalProfile = version.rtq + "globalProfile.jsp";
DBHelper.URLs.saveconfigurl = version.rtq + "saveWsConfig.jsp";
DBHelper.URLs.captureWorkspace = version.rtq + "captureWorkspace.jsp";
DBHelper.URLs.captureComponent = version.rtq + "captureComponent.jsp";
DBHelper.URLs.timesales = PULL_Path+"getTimeSales.jsp";/* 20091201 by wind yao */
DBHelper.URLs.calendar= version.rtq + "getCalendar.jsp";/* 20100311 by yuntao zhou */
DBHelper.URLs.commodity= version.rtq + "getCommodity.jsp";/* 20100311 by yuntao zhou */
DBHelper.URLs.exportTimeSales = version.rtq + "exportTimeAndSaleData.jsp";
DBHelper.URLs.getNewsContentURL=version.rtq +"getNewsContent.jsp";
DBHelper.URLs.LPLportfolio = version.rtq + "LPLportfolio.jsp";/* add for LPL portfolio*/
DBHelper.URLs.workspacemanagement = version.rtq+"workspacemanagement.jsp";//20110107 by jacky for workspace management
DBHelper.URLs.portfolioSummary = PULL_Path+"getPortfolioSummary.jsp";
DBHelper.URLs.datamanagement=version.rtq+"notedatamanagement.jsp";
DBHelper.URLs.forexHistoricalData=version.rtq+"getForexHistoricalData.jsp";
DBHelper.URLs.messageModuleURL=version.rtq+"message.jsp"; //20110509 by songlin for message
DBHelper.URLs.shareSender=version.rtq+"shareSender.jsp";
DBHelper.URLs.alertManagement=version.rtq+"alertmanagement.jsp";
DBHelper.URLs.defaultWatchlist=version.rtq+"getdefaultwatchlist.jsp";
DBHelper.URLs.getConstituents=version.rtq+"getHoldingViewJASON.jsp";
DBHelper.sectorUrl=version.rtq+"advancedSearch.jsp";
DBHelper.URLs.searchData=version.rtq+'advancedSearch.jsp';
DBHelper.URLs.searchExport=version.rtq+'exportSearchToFile.jsp';
DBHelper.TIMEOUT=10000;

DBHelper.openWindowWithPost=function(data){
    var el=null;
	data.instid=GOLBAL_DATA.ProductCode;
    if (typeof(window.frames["export"]) == 'undefined') {
        var html = "<div class='export' style='display:none;'>";
        html += "<form id='exportform' name='exportform' method='post' action='" + DBHelper.URLs.searchExport + "' target='export'>";
        html += "</form>";
        html += "<iframe id='export' name='export' style='display:none;'></iframe>";
        html += "</div>";
        el=$(html).appendTo($('body'));
    }else{
        el=$('body');
    }
    var form=el.find("form#exportform");
    form.empty();
    var element="";
    for (var item in data) {
        element+="<input type='hidden' name='" + item + "' value='"+data[item]+"'/>";
    }
    form.append(element);
    form.submit();
};
DBHelper.getConstituents=function(sid,callback){
	if (QS_UserID != null) {
        $.getJSON(DBHelper.URLs.getConstituents, {secId:sid,t:new Date().getTime()}, callback);
    }
};
DBHelper.getMessageList=function(list,callbak){
	if (QS_UserID != null) {
        $.post(DBHelper.URLs.messageModuleURL, list, callbak);
    }
};
DBHelper.getContact=function(filter,callback){
    if (QS_UserID != null) {
		var data={
			type:"getContact",
			filter:filter==null?'':filter
		}
        $.post(DBHelper.URLs.shareSender,data,callback);
    }
};
DBHelper.sendMessage=function(data,callback){
	if (QS_UserID != null) {
		data.type="sendMessage";
        $.post(DBHelper.URLs.shareSender,data,callback);
    }
};
DBHelper.sendShare=function(data,callback){
    if (QS_UserID != null) {
		data.type="sendShare";
        $.post(DBHelper.URLs.shareSender,data,callback);
    }
};
DBHelper.getShareData=function(data,callback){
    if (QS_UserID != null) {
        data.type="getShare";
        $.post(DBHelper.URLs.shareSender,data,callback);
    }
};
DBHelper.saveCurrentWorkspaceProfile=function(id,profile,updateTime){
	if (QS.localStorageLock&&window.localStorage) {
		var arr = [["QS_CurWsId_" + QS_UserID, id], ["QS_CurWs_" + QS_UserID, profile], ["QS_CurWs_UpdatedTime_" + QS_UserID, updateTime]];
		save2LocalStorage(arr);
	}
};
DBHelper.saveLocalPortfolioList=function(list,updateTime){
	if (QS.localStorageLock&&window.localStorage) {
		var arr = [["QS_Pfl_" + QS_UserID, list], ["QS_Pfl_UpdatedTime_" + QS_UserID, updateTime]];
		save2LocalStorage(arr);
		if (GOLBAL_DATA.terminalGlobalProfile.LastPflUpdateTime != updateTime) {
			Terminal.setConfig({
				LastPflUpdateTime: updateTime
			});
		}
	}
};
DBHelper.updateLocalPortfolio=function(portfolio,updateTime,cmd){
	if (QS.localStorageLock&&window.localStorage) {
		var Portfolios=localStorage.getItem("QS_Pfl_" + QS_UserID);
		if(Portfolios&&Portfolios!=''){
			Portfolios=$.evalJSON(Portfolios).Portfolios;
		}
		if(Portfolios.length>0){
			if(cmd=='add'){
				Portfolios.push(portfolio);
			}else{
				var idx=-1;
				for(var i=0,l=Portfolios.length;i<l;i++){
					if(portfolio.PfId==Portfolios[i].PfId){
						idx=i;
						break;
					}
				}
				if (idx != -1) {
					if (cmd == 'del') {
						Portfolios.splice(idx, 1);
					}
					else if (cmd == 'update') {
						$.extend(Portfolios[idx],portfolio);
					}
				}
			}
			var arr=[["QS_Pfl_"+QS_UserID,$.toJSON({Portfolios:Portfolios,UpdateTime:updateTime})],["QS_Pfl_UpdatedTime_"+QS_UserID,updateTime]];
	        save2LocalStorage(arr);
	        if(GOLBAL_DATA.terminalGlobalProfile.LastPflUpdateTime != updateTime&&window.localStorage){
	            Terminal.setConfig({
	                LastPflUpdateTime: updateTime    
	            });
	        }
		}
	}
};
//Template
DBHelper.getWidgetTemplate = function(TemplateId, callback){
    if (QS_UserID != null) {
        var data = { tplId: TemplateId.toString().replace(/[^0-9]/g, ''), action:'gettmp', tmpid:QS_UserTID };
        DBHelper.post(DBHelper.URLs.template, data, callback);
    }
};
DBHelper.getWidgetTemplateListByType = function(TemplateType, callback){
    if (QS_UserID != null) {
        var data = { type: TemplateType, action:'gettmplist', tmpid:QS_UserTID };
        DBHelper.unrepost(DBHelper.URLs.template,data,callback,null,true);
    }
};
DBHelper.insertWidgetTemplate = function(type, profile, callback){
    var pro = $.toJSON(profile);
    if (QS_UserID != null) {
        var data = {
            type: type,
            profile: pro,
            title: profile.title,
            action: 'addtmp', 
            tmpid: QS_UserTID
        };
        DBHelper.post(DBHelper.URLs.template, data, callback);
    }
};
DBHelper.saveWidgetTemplate = function(TemplateId, profile, callback){
    var pro = $.toJSON(profile);
    if (QS_UserID != null) {
        var data = {
            tplId: TemplateId,
            profile: pro,
            action: 'savetmp',
            tmpid: QS_UserTID
        };
        DBHelper.post(DBHelper.URLs.template, data, callback);
    }
};
DBHelper.deleteWidgetTemplate = function(TemplateId, callback){
    if (QS_UserID != null) {
        var data = { tplId: TemplateId, action:'deltmp', tmpid: QS_UserTID};
        DBHelper.post(DBHelper.URLs.template, data, callback);
    }
};

//GlobalProfile
DBHelper.setGlobalProfile = function(profile, callback){
    if (QS_UserID != null) {
        var data = { profile: $.toJSON(profile), action:'setprofile', tmpid: QS_UserTID, uid:QS_UserID};
        DBHelper.post(DBHelper.URLs.globalProfile, data, callback);
    }
};
DBHelper.getGlobalProfile = function(callback){
    if (QS_UserID != null) {
        var data = { action:'getprofile', tmpid: QS_UserTID, uid:QS_UserID};
        DBHelper.post(DBHelper.URLs.globalProfile, data, callback);
    }
};
//search data
DBHelper.getOptionsByCode=function(values,callback){
    //type:advanced,option
    var data = {type:'option',fields:values.join(',')};
    DBHelper.post(DBHelper.URLs.searchData, data, callback);
};
DBHelper.getSearchResult = function(data, callback){
     data.type="ticker";
	 data.instid=GOLBAL_DATA.ProductCode;
     DBHelper.post(DBHelper.URLs.searchData, data, callback);
};
DBHelper.getRangeByCode=function(data,callback){
    //type:advanced,option
    var data = {type:'advanced',instid:GOLBAL_DATA.ProductCode,query:$.toJSON(data.query),fields:data.fields.join(',')};
    DBHelper.post(DBHelper.URLs.searchData, data, callback);
};
DBHelper.insertWorkspace = function(workspace, callback){ // ws:formate {id:-1,profile:{name:"myspace"}}
    callback = callback||function(){};
    if (QS_UserID != null) {
        var data = { workspace: $.toJSON(workspace), uid:QS_UserID, tmpid: QS_UserTID};
        $.post(DBHelper.URLs.saveconfigurl, data, callback);
    }
};
DBHelper.saveWorkspace = function(workspace, wsID, widgets, callback){ // ws:formate {id:-1,profile:{name:"myspace"}}
    callback = callback||function(){};
    if (QS_UserID != null) {
        var data = { workspace: $.toJSON(workspace), wsId:wsID, widgets: $.toJSON(widgets), uid:QS_UserID, tmpid: QS_UserTID};
        $.post(DBHelper.URLs.saveconfigurl, data, callback);
    }
};
DBHelper.saveWorkspaceName = function(workspace, wsID, callback){ // ws:formate {id:-1,profile:{name:"myspace"}}
    callback = callback||function(){};
    if (QS_UserID != null) {
        var data = { workspace: $.toJSON(workspace), wsId:wsID, action:"rename",uid:QS_UserID, tmpid: QS_UserTID};
        $.post(DBHelper.URLs.saveconfigurl, data, callback);
    }
};
//Workspace screenshot
DBHelper.captureWorkspace = function(wsID, callback){
    callback = callback||function(){};
    if (QS_UserID != null) {
        var data = { wsId:wsID, tmpid: QS_UserTID};
        $.post(DBHelper.URLs.captureWorkspace, data, callback);
    }
};
//Component screenshot
DBHelper.captureComponent=function(wsId,cpId,cpType,callback){
    callback = callback||function(){};
    if (QS_UserID != null) {
        var data = { wsId:wsId,cpId:cpId,cpType:cpType,tmpid: QS_UserTID};
        $.post(DBHelper.URLs.captureComponent, data, callback);
    }
};
//.com portfolio
DBHelper.getPortfolio = function(PortfolioId, callback){
    if (QS_UserID != null) {
        var data = { pflId: PortfolioId, action:'getpfl', usrname:Cookies.get("UsrName"), tmpid: QS_UserTID};
        $.post(DBHelper.URLs.portfolio, data, callback);
    }
};
DBHelper.getPortfolioList = function(callback){
    if (QS_UserID != null) {
		var flag = false, pList;
		if (QS.localStorageLock&&window.localStorage) {
			var serverTime = Terminal.getConfig("LastPflUpdateTime");//DB Time
			var clientTime = localStorage.getItem("QS_Pfl_UpdatedTime_"+QS_UserID);//Client Time
			pList = localStorage.getItem("QS_Pfl_"+QS_UserID);
			if (compareTime(clientTime,serverTime)>=0 && pList && pList != '') {
				flag = true;
			}
		}
		if (flag) {
			callback(pList);
		}else{
			var data = {
				action: 'getpfllist',
				usrname: Cookies.get("UsrName"),
				tmpid: QS_UserTID
			};
			//$.post(DBHelper.URLs.portfolio, data, callback);
			DBHelper.unrepost(DBHelper.URLs.portfolio, data, callback,DBHelper.TIMEOUT);
	   }
	}
};
DBHelper.insertPortfolio = function(title, tickers, callback, type){ //0 pl, 0 wl
    if (QS_UserID != null) {
        var data = { action:'addpfl', title:title, usrname:Cookies.get("UsrName"), currency:'USD', type:type, list:tickers, tmpid: QS_UserTID};
        $.post(DBHelper.URLs.portfolio, data, callback);
    }
};
DBHelper.updatePortfolio = function(PortfolioId, tickers, callback){
    if (QS_UserID != null) {
        var data = { pflId: PortfolioId, action:'updatepfl', list:tickers, usrname:Cookies.get("UsrName"), tmpid: QS_UserTID};
        $.post(DBHelper.URLs.portfolio, data, callback);
    }
};
DBHelper.deletePortfolio = function(PortfolioId, callback){
    if (QS_UserID != null) {
        var data = { pflId: PortfolioId, action:'delpfl', usrname:Cookies.get("UsrName"), tmpid: QS_UserTID};
        $.post(DBHelper.URLs.portfolio, data, callback);
    }
};
DBHelper.renamePortfolio = function(title,PortfolioId,type,callback){
	if (QS_UserID != null) {
        var data = { pflId: PortfolioId,action:'rename', title:title, usrname:Cookies.get("UsrName"), type:type, tmpid: QS_UserTID};
        $.post(DBHelper.URLs.portfolio, data, callback);
    }
}
DBHelper.getPortfolioSummary = function(PortfolioId,list,type,callback){
    if (QS_UserID != null) {
        var data = { pflId: PortfolioId, list:list,type:type,usrname:Cookies.get("UsrName"), tmpid: QS_UserTID};
        //DBHelper.post(DBHelper.URLs.portfolioSummary,data,callback);
        //$.post(DBHelper.URLs.portfolio, data, callback);
		$.getJSON(DBHelper.URLs.portfolioSummary+"?cb=?",data,callback)
    }
};
// ajax request
DBHelper.post = function(url,data,callback,timeout){
	$.ajax({
		type:'POST',
		url:url,
		cache:false,
		timeout:timeout?timeout:null,
		data:$.param(data), 
        success:function(data){
			callback(data);
		},
		error:function(){
			callback("error");
		}
	});
}

DBHelper.unrepost = function(){
    var cacheCallback={};//{"id":{status:true,callback:[]}}
    return function(url,data,callback,time,disarg){
        var id=url;
        if(disarg){
            id=url+"?"+$.param(data);
        }
        if(!cacheCallback[id]||cacheCallback[id].status){
            cacheCallback[id]={status:true,callbacks:[]};
            if(typeof callback=='function'){
                cacheCallback[id].callbacks.push(callback);
            }
            cacheCallback[id].status=false;
            DBHelper.post(url,data,function(data){
                with({copy:id}){
                    while(cacheCallback[copy].callbacks.length>0){
                        cacheCallback[copy].callbacks.shift()(data);
                    }
                    cacheCallback[copy].status=true;
                }
            },time);
        }else{
            if(typeof callback=='function'){
                cacheCallback[id].callbacks.push(callback);
            }
        }
    };
}();

// LPLHouseholdlist
DBHelper.getLPLHouseholdlist = function(callback){
    if (QS_UserID != null) {
        var data = {action:'getHouseholdlist', usrname:Cookies.get("UsrName"), tmpid: QS_UserTID};
        //$.post(DBHelper.URLs.LPLportfolio, data, callback);
        DBHelper.unrepost(DBHelper.URLs.LPLportfolio, data, callback);
	}
};
DBHelper.getLPLHouseholdHoldings = function(householdId,callback){
	if (QS_UserID != null) {
        var data = {householdId:householdId, action:'getHouseholdHoldings', usrname:Cookies.get("UsrName"), tmpid: QS_UserTID};
        $.post(DBHelper.URLs.LPLportfolio, data, callback);
    }
};
DBHelper.getLPLPracticeHoldings = function(repId,groupBy,callback){
    if (QS_UserID != null) {
        var data = {repId:repId,action:'getPracticeHoldings',groupBy:groupBy, usrname:Cookies.get("UsrName"), tmpid: QS_UserTID};
        $.post(DBHelper.URLs.LPLportfolio, data, callback);
    }
};

//time & sales by wind yao 20091201
DBHelper.exportTimeSales = function(pullKey,callback){
    if (QS_UserID != null) {
		var url = DBHelper.URLs.exportTimeSales+"?t="+pullKey;
        window.open(url);
    }
};
//time & sales by wind yao 20091201
DBHelper.getTimeSales = function(pullKey,callback){
    if (QS_UserID != null) {
        var data = {t:pullKey};
        $.getJSON(DBHelper.URLs.timesales+"?cb=?", data, callback);
    }
};
//20100311 by yuntao zhou 
DBHelper.getCalendar = function(type,date,serviceCode,callback){
    if (QS_UserID != null) {
        var data = {type:type,date:date,serviceCode:serviceCode};
        $.post(DBHelper.URLs.calendar, data, callback);
    }
};
//20100402 by yuntao zhou 
DBHelper.getCommodity = function(type,callback){
    if (QS_UserID != null) {
        var data = {type:type};
        $.post(DBHelper.URLs.commodity, data, callback);
    }
};
//20110107 by jacky for workspace management
DBHelper.workspacemanagement=function(data,callback){
	if (QS_UserID != null) {
        $.post(DBHelper.URLs.workspacemanagement+"?time="+new Date().getTime(), data, callback);
    }
};
DBHelper.newLabel=function(wsname,callback){
	DBHelper.workspacemanagement({action:"newlabel",wsname:wsname},callback);
};
DBHelper.renameLabel=function(categoryid,categoryname,callback){
	DBHelper.workspacemanagement({action:"renamelabel",categoryid:categoryid,categoryname:categoryname},callback);
};
DBHelper.deleteLabel=function(removecategroyid,callback){
	DBHelper.workspacemanagement({action:"deletelabel",removecategroyid:removecategroyid},callback);
};
DBHelper.workspaceAddLabel=function(wsid,targetCategroyId,callback){
	DBHelper.workspacemanagement({action:"workspaceaddlabel",wsid:wsid,targetcategroyid:targetCategroyId},callback);
};
DBHelper.moveWorkspace=function(wsid,sourceCategroyId,targetCategroyId,callback){
	DBHelper.workspacemanagement({action:"moveworkspace",wsid:wsid,sourcecategroyid:sourceCategroyId,targetcategroyid:targetCategroyId},callback);
};
DBHelper.newLabelAndMoveWorkspace=function(wsid,sourcecategroyid,wsname,callback){
	DBHelper.workspacemanagement({action:"newlabelandmoveworkspace",wsid:wsid,sourcecategroyid:sourcecategroyid,wsname:wsname},callback);
};
DBHelper.newLabelAndLabelWorkspace=function(wsid,wsname,callback){
	DBHelper.workspacemanagement({action:"newlabelandlabelworkspace",wsid:wsid,wsname:wsname},callback);
};
DBHelper.updateWorkspaceLabels=function(wsid,maps,callback){
	DBHelper.workspacemanagement({action:"updateworkspacelabels",wsid:wsid,maps:maps},callback);
};
DBHelper.getWorkspaceCategoryList=function(wsid,callback){
	DBHelper.workspacemanagement({action:"getworkspacecategorylist",wsid:wsid},callback);
};
DBHelper.getCategoryWorkspaceList=function(categoryid,callback){
	DBHelper.workspacemanagement({action:"getcategoryworkspacelist",categoryid:categoryid},callback);
};
DBHelper.getAllCategroylist=function(callback){
	DBHelper.workspacemanagement({action:"getcategroylist"},callback);
};
//20110215 by jacky for chart note datamangement
DBHelper.datamanagement=function(data,callback){
	if (QS_UserID != null) {
        $.post(DBHelper.URLs.datamanagement+"?time="+new Date().getTime(), data, callback);
    }
};
DBHelper.addNote=function(pid,saveinfo,date,callback){
	DBHelper.datamanagement({action:"addnote",pid:pid,saveinfo:saveinfo,date:date},callback);
};
DBHelper.updateNote=function(nid,pid,saveinfo,date,callback){
	DBHelper.datamanagement({action:"updatenote",nid:nid,pid:pid,saveinfo:saveinfo,date:date},callback);
};
DBHelper.removeNote=function(nid,callback){
	DBHelper.datamanagement({action:"removenote",nid:nid},callback);
};
DBHelper.loadNotesByDate=function(pid,startDate,endDate,callback){
	DBHelper.datamanagement({action:"loadnotesbydate",pid:pid,startdate:startDate,enddate:endDate},callback);
};

DBHelper.forexHistoricalData=function(data,callback){
    if (QS_UserID != null) {
        $.post(DBHelper.URLs.forexHistoricalData+"?time="+new Date().getTime(), data, callback);
    }
};
//20110524 by jacky for alert management
DBHelper.alertmanagement=function(data,callback){
    if (QS_UserID != null) {
        $.post(DBHelper.URLs.alertManagement+"?time="+new Date().getTime(), data, callback);
    }
};
DBHelper.addAlert=function(alerttype,idtype,symbol,displayTicker,value,label,email,emailaddr,callback){
    DBHelper.alertmanagement({action:"insert",alerttype:alerttype,idtype:idtype,symbol:symbol,displayTicker:displayTicker,value:value,label:label,email:email,emailaddr:emailaddr},callback);
};
DBHelper.operateAlert=function(alertid,email,type,callback){
    DBHelper.alertmanagement({action:"operate",alertid:alertid,emailaddr:email,operatetype:type},callback);
};
DBHelper.updateAlert=function(alertid,alerttype,value,label,email,emailaddr,callback){
    DBHelper.alertmanagement({action:"update",alertid:alertid,alerttype:alerttype,value:value,label:label,email:email,emailaddr:emailaddr},callback);
};
DBHelper.updateEmail=function(emailaddr,callback){
    DBHelper.alertmanagement({action:"updateemail",emailaddr:emailaddr},callback);
};
DBHelper.deleteAlert=function(alertid,email,callback){
    DBHelper.alertmanagement({action:"operate",alertid:alertid,emailaddr:email,operatetype:0},callback);
};
DBHelper.getAllAlerts=function(callback,order){
    DBHelper.alertmanagement({action:"getalerts",order:order},callback);
};
DBHelper.saveAlertConfig=function(saveconfig,callback){
    DBHelper.alertmanagement({action:"saveconfig",saveconfig:saveconfig},callback);
};
DBHelper.loadAlertLog=function(callback){
    DBHelper.alertmanagement({action:"loadlog"},callback);
};

//load default watchlist from server,2011.9.14,alex
DBHelper.getDefaultWatchlist = function(callback){
    if (QS_UserID != null) {
        var data = {action:"getwatchlist"};
        DBHelper.unrepost(DBHelper.URLs.defaultWatchlist, data, callback);
    }
};

//load default watchlist from server,2011.9.14,alex
DBHelper.getDefaultTickersByWatchId=function(watchId,callback){
	if (QS_UserID != null) {
		var data = {action:"gettickers",watchId:watchId};
        DBHelper.post(DBHelper.URLs.defaultWatchlist, data, callback);
    }
};